// DEPRECATED: This file is for legacy support only.
// Please use multi-chain-api.ts for all new API calls.
// This client only supports the default chain and should not be used for multi-chain operations.

import axios, { AxiosError, AxiosInstance } from 'axios';
import { API_BASE_URL } from '@/config/api';
import { getAuthToken, removeAuthToken, setAuthToken } from './auth';
import { DEFAULT_CHAIN } from '@/config/chains';
import toast from 'react-hot-toast';

// Create axios instance
const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor to add auth token
apiClient.interceptors.request.use(
  (config) => {
    // Legacy support - use default chain
    const token = getAuthToken(DEFAULT_CHAIN);
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor for error handling
apiClient.interceptors.response.use(
  (response) => response,
  async (error: AxiosError) => {
    const originalRequest = error.config as any;
    
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      // Try to refresh token
      try {
        const refreshToken = localStorage.getItem('refresh_token');
        if (refreshToken) {
          const response = await axios.post(`${API_BASE_URL}/api/v1/auth/refresh`, {
            refresh_token: refreshToken,
          });
          
          const { access_token } = response.data;
          setAuthToken(access_token, DEFAULT_CHAIN);
          
          // Retry original request
          originalRequest.headers.Authorization = `Bearer ${access_token}`;
          return apiClient(originalRequest);
        }
      } catch (refreshError) {
        // Refresh failed, redirect to login
        removeAuthToken(DEFAULT_CHAIN);
        window.location.href = '/login';
      }
    }
    
    // Show error toast for other errors
    if (error.response?.status !== 401) {
      const message = (error.response?.data as any)?.detail || 'An error occurred';
      toast.error(message);
    }
    
    return Promise.reject(error);
  }
);

export default apiClient;